package com.example.poweralert;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Space;
import android.widget.Toast;

public class MainActivity extends Activity {
	
	private Context mContext = this;
	private SharedPreferences mSP;

	private Button btnOK;
	private EditText etPhone;
	
	private boolean isAlertOpen = false;
	private String sAlertPhone = "";
	
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initView();
        checkAlertStatus();
        
    	Intent intent = new Intent(this, PAService.class);
    	startService(intent);
    }
    
    private void initView(){
    	mSP = getSharedPreferences("PA", MODE_PRIVATE);
    	
    	isAlertOpen = mSP.getBoolean(Constants.SP_ALERT_OPEN_FLAG, false);
    	sAlertPhone = mSP.getString(Constants.SP_ALERT_PHONE, "");
    	
    	btnOK = (Button) findViewById(R.id.btnOK);
    	btnOK.setOnClickListener(mOnClickListener);
    	
    	etPhone = (EditText) findViewById(R.id.etPhone);
    	etPhone.setText(sAlertPhone);
    }
    
    
    private OnClickListener mOnClickListener = new OnClickListener() {
		
		@Override
		public void onClick(View v) {
			// TODO Auto-generated method stub
			int id = v.getId();
			switch(id) {
			case R.id.btnOK:
				pressOKButton();
				break;
			default:
				break;
			}
		}
	};
	
	private void checkAlertStatus(){
		if(isAlertOpen) {
    		etPhone.setEnabled(false);
    		btnOK.setText("关闭");
    		Toast.makeText(this, "已打开断电监听", Toast.LENGTH_SHORT).show();
    	} else {
    		etPhone.setEnabled(true);
    		btnOK.setText("开启");
    		Toast.makeText(this, "已关闭断电监听", Toast.LENGTH_SHORT).show();
    	}
	}
	
	private void pressOKButton(){
		
		///Intent intentPhone = new Intent(Intent.ACTION_CALL,Uri.parse("tel:"+"15800076303"));  
		//startActivity(intentPhone); 
		
		isAlertOpen = !isAlertOpen;
		
		Log.i("dvlee", isAlertOpen + "");
		mSP.edit().putBoolean(Constants.SP_ALERT_OPEN_FLAG, isAlertOpen).commit();
		if(isAlertOpen) {
			mSP.edit().putString(Constants.SP_ALERT_PHONE, etPhone.getText().toString()).commit();
		}
		checkAlertStatus();
	}
    

}
